package com.magist.manage.task;

import com.google.common.collect.Lists;
import com.jeesuite.common.util.DateUtils;
import com.magist.core.constants.Deleted;
import com.magist.core.util.DateUtil;
import com.magist.core.util.SendEmailUtils;
import com.magist.manage.copyrights.entity.ContractRights;
import com.magist.manage.copyrights.entity.Copyrights;
import com.magist.manage.copyrights.entity.SupplyContract;
import com.magist.manage.copyrights.entity.SupplyInfo;
import com.magist.manage.copyrights.service.ContractRightsService;
import com.magist.manage.copyrights.service.CopyrightsService;
import com.magist.manage.copyrights.service.SupplyContractService;
import com.magist.manage.copyrights.service.SupplyInfoService;
import com.magist.manage.email.service.EmailSender;
import com.magist.manage.enums.SupplyStatusEnum;
import com.magist.manage.web.entity.MailAcceptUsers;
import com.magist.manage.web.entity.UserLogin;
import com.magist.manage.web.service.MailAcceptUsersService;
import com.magist.manage.web.service.UserLoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class MailSendTask {

    Logger logger = LoggerFactory.getLogger(MailSendTask.class);

    @Autowired
    private MailAcceptUsersService mailAcceptUsersService;

    @Autowired
    private SupplyContractService supplyContractService;


    @Qualifier("supplyContractEmailSenderImpl")
    @Autowired
    private EmailSender supplyContractEmailSender;

    @Qualifier("copyrightsEmailSenderImpl")
    @Autowired
    private EmailSender copyrightsEmailSender;

    @Qualifier("contractRightsEmailSenderImpl")
    @Autowired
    private EmailSender contractRightsEmailSender;

    @Qualifier("supplyInfoEmailSenderImpl")
    @Autowired
    private EmailSender supplyInfoEmailSender;


    @Autowired
    private CopyrightsService copyrightsService;
    @Autowired
    private ContractRightsService contractRightsService;
    @Autowired
    private SupplyInfoService supplyInfoService;
    @Autowired
    private UserLoginService userLoginService;


    // 每天早上8点
    @Scheduled(cron = "0 0 8 * * ?")
    public void supplyContractEmail() {
        // 查询1月过期的
        List<SupplyContract> supplyContracts_one = supplyContractService.findNearlyExpire(1);
        // 查询3月过期的
        List<SupplyContract> supplyContracts_three = supplyContractService.findNearlyExpire(3);
        // 查询6月过期的
        List<SupplyContract> supplyContracts_six = supplyContractService.findNearlyExpire(6);

        List<MailAcceptUsers> mailAcceptUsersList = mailAcceptUsersService.findAll();

        if (!CollectionUtils.isEmpty(mailAcceptUsersList)) {

            mailAcceptUsersList.forEach(user -> {
                String mailAddress = user.getMailAddress();
                if (!StringUtils.isEmpty(mailAddress)) {
                    String subject = "以下合同1个月内即将过期";
                    supplyContractEmailSender.sendEmail(supplyContracts_one, subject, mailAddress);
                    subject = "以下合同3个月内即将过期";
                    supplyContractEmailSender.sendEmail(supplyContracts_three, subject, mailAddress);
                    subject = "以下合同6个月内即将过期";
                    supplyContractEmailSender.sendEmail(supplyContracts_six, subject, mailAddress);

                }
            });
        }
        logger.info("发送合同到期邮件执行完成");
    }


    // 8.05
    @Scheduled(cron = "0 5 8 * * ?")
    public void copyrightsEmail() {
        List<Copyrights> copyrightses_one = copyrightsService.findNearlyExpire(1);
        List<Copyrights> copyrightses_three = copyrightsService.findNearlyExpire(3);
        List<Copyrights> copyrightses_six = copyrightsService.findNearlyExpire(6);

        List<MailAcceptUsers> mailAcceptUsersList = mailAcceptUsersService.findAll();
        if (!CollectionUtils.isEmpty(mailAcceptUsersList)) {

            mailAcceptUsersList.forEach(user -> {
                String mailAddress = user.getMailAddress();
                if (!StringUtils.isEmpty(mailAddress)) {
                    String subject = "以下版权1个月内即将过期";
                    copyrightsEmailSender.sendEmail(copyrightses_one, subject, mailAddress);
                    subject = "以下版权3个月内即将过期";
                    copyrightsEmailSender.sendEmail(copyrightses_three, subject, mailAddress);
                    subject = "以下版权6个月内即将过期";
                    copyrightsEmailSender.sendEmail(copyrightses_six, subject, mailAddress);
                }
            });
        }
        logger.info("发送版权到期邮件执行完成");
    }

    // 8.10
    @Scheduled(cron = "0 10 8 * * ?")
    public void contractRightsEmail() {
        List<ContractRights> contractRightses_one = contractRightsService.findNearlyExpire(1);
        List<ContractRights> contractRightses_three = contractRightsService.findNearlyExpire(3);
        List<ContractRights> contractRightses_six = contractRightsService.findNearlyExpire(6);
        List<MailAcceptUsers> mailAcceptUsersList = mailAcceptUsersService.findAll();
        if (!CollectionUtils.isEmpty(mailAcceptUsersList)) {

            mailAcceptUsersList.forEach(user -> {
                String mailAddress = user.getMailAddress();
                if (!StringUtils.isEmpty(mailAddress)) {
                    String subject = "以下授权1个月内即将过期";
                    contractRightsEmailSender.sendEmail(contractRightses_one, subject, mailAddress);
                    subject = "以下授权3个月内即将过期";
                    contractRightsEmailSender.sendEmail(contractRightses_three, subject, mailAddress);
                    subject = "以下授权6个月内即将过期";
                    contractRightsEmailSender.sendEmail(contractRightses_six, subject, mailAddress);
                }
            });
        }
        logger.info("发送授权到期邮件执行完成");
    }


    // 8.15
    @Scheduled(cron = "0 15 8 * * ?")
    public void supplyInfoEmail() {
        Example example = new Example(SupplyInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.orEqualTo("status", SupplyStatusEnum.LIANXI.getCode());
        criteria.orEqualTo("status", SupplyStatusEnum.WAIT.getCode());
        criteria.orEqualTo("status", SupplyStatusEnum.YIXIANG.getCode());
        Date dayBegin = DateUtils.getDayBegin(new Date());
        Date endDate = DateUtils.addWeeks(dayBegin, 3);
        criteria.andGreaterThanOrEqualTo("modifyTime", endDate);
        List<SupplyInfo> supplyInfos = supplyInfoService.find(example);

        List<SupplyInfo> filteSupplys = supplyInfos.stream().filter(supplyInfo -> {
            try {
                return DateUtil.daysBetween(DateUtils.getDayBegin(supplyInfo.getModifyTime()), dayBegin) % 7 == 0;
            } catch (Exception e) {
                return false;
            }
        }).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(filteSupplys)) {
            filteSupplys.forEach(supplyInfo -> {
                String personId = supplyInfo.getPersonId();
                UserLogin userLogin = userLoginService.getById(personId);
                if (!ObjectUtils.isEmpty(userLogin)) {
                    String email = userLogin.getEmail();
                    if (!StringUtils.isEmpty(email)) {
                        try {
                            int i = DateUtil.daysBetween(DateUtils.getDayBegin(supplyInfo.getModifyTime()), dayBegin);
                            String subject = "以下供应商" + i/7 + "周未联系";
                            supplyInfoEmailSender.sendEmail(Lists.newArrayList(supplyInfo),subject,email);
                        } catch (Exception e) {

                        }

                    }
                }
            });
        }
        logger.info("发送供应商沟通提醒邮件执行完成");
    }


    /********
     *这是最简单的2种方式，多少分钟执行一次，fixedDelay和fixedRate，单位是毫秒，所以1分钟就是60秒×1000
     * 他们的区别在于，fixedRate就是每多次分钟一次，不论你业务执行花费了多少时间。我都是1分钟执行1次，而fixedDelay是当任务执行完毕后1分钟在执行。所以根据实际业务不同，我们会选择不同的方式。


     * 第一位，表示秒，取值0-59
     * 第二位，表示分，取值0-59
     * 第三位，表示小时，取值0-23
     * 第四位，日期天/日，取值1-31
     * 第五位，日期月份，取值1-12
     * 六位，星期，取值1-7，星期一，星期二...，注：不是第1周，第二周的意思另外：1表示星期天，2表示星期一。
     * 第7为，年份，可以留空，取值1970-2099
     *
     * 0 0 3 * * ?     每天3点执行
     * 0 5 3 * * ?     每天3点5分执行
     * 0 5 3 ? * *     每天3点5分执行，与上面作用相同
     * 0 5/10 3 * * ?  每天3点的 5分，15分，25分，35分，45分，55分这几个时间点执行
     * 0 10 3 ? * 1    每周星期天，3点10分 执行，注：1表示星期天
     * 0 10 3 ? * 1#3  每个月的第三个星期，星期天 执行，#号只能出现在星期的位置
     *
     * 作者：陶清清
     * 链接：https://www.jianshu.com/p/ef18af5a9c1d
     * 來源：简书
     * 简书著作权归作者所有，任何形式的转载都请联系作者获得授权并注明出处。
     * *********/


    //标题，内容，收件人邮箱
    public void sendEmail(String subject, String content) {
        MailAcceptUsers temp = new MailAcceptUsers();
        temp.setDeleted(Deleted.NO_STR);
        List<MailAcceptUsers> mailAcceptUsersList = mailAcceptUsersService.find(temp);
        if (!CollectionUtils.isEmpty(mailAcceptUsersList)) {
            for (MailAcceptUsers m : mailAcceptUsersList) {
                if (!StringUtils.isEmpty(m.getMailAddress())) {
                    SendEmailUtils.sendEmail(subject, content, m.getMailAddress());
                }
            }
        }
    }



    private  void sendEmailTask(){

    }
}
